﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel ;
using System.Linq;
using System.Text;
using System.Management.Automation.Runspaces;
using System.Management.Automation;

namespace HyperVGuestToolbox
{
    static class PSHelper
    {
        public static Collection<PSObject> ExecuteCommands(IEnumerable<string> commands)
        {
        
            System.Diagnostics.Debug.Print(String.Join("\n", commands.ToArray()));
            //Connect to the Virtual Server and find the current image

            //read the registry to check if we are in a VM and to get the host
            //HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters

            //Get the VMGuest
            //Get-VM $VMReg.VirtualMachineName -server $VMReg.PhysicalHostNameFullyQualified
            //$DVD = Get-VMDisk $vm |?{$_.DriveName -eq "DVD Drive"}

            RunspaceConfiguration rconfig = RunspaceConfiguration.Create();
            PSSnapInException Pwarn = new PSSnapInException();

            //Can't use remoting and use the get-vm cmdlets :(
            //WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://admin01/wsman"));

            Runspace runspace = RunspaceFactory.CreateRunspace();

            //This needs to be installed on the machine which I can't assume
            //runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SystemCenter.VirtualMachineManager", out Pwarn);    

            runspace.Open();


            Pipeline pipeline = runspace.CreatePipeline();


            //Collection<PSObject> results = new Collection<PSObject>();


            try
            {
              
                pipeline.Commands.AddScript(String.Join("\n",commands.ToArray()));
                
                return pipeline.Invoke();
          

                /*foreach (var item in results)
                {

                    foreach (var prop in item.Properties)
                    {
                        System.Diagnostics.Debug.Print("{0}##{1}\n", prop.Value, prop.Name);
                    }
                }
                 * */
                //string n = (string)results[0].Properties["Name"].Value;
            }

            catch (Exception ex)
            {
               // throw ex;
                return null;
            }

            finally
            {
                runspace.Close();
                runspace.Dispose();

            }
        }
    }
}
